#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

enum character
{
    creater,
    user
};

#define READ O_RDONLY
#define WRITE O_WRONLY
#define MAXSIZE 2048
const std::string fifopath = "./myfifo";
class namedPipe
{
public:
    namedPipe(character id)
        : _fifoPath(fifopath), _ch(id), _fd(-1)
    {
        if (_ch == creater)
        {
            if (mkfifo(fifopath.c_str(), 0666) < 0)
                perror("mkfifo");

            std::cout << "creater create fifo" << std::endl;
        }
    }

    ~namedPipe()
    {
        if (_ch == creater)
        {
            if (unlink(fifopath.c_str()) < 0)
                perror("unlink");

            std::cout << "creater free fifo" << std::endl;
        }

        if (_fd != -1)
        {
            close(_fd);
            std::cout << "close file" << std::endl;
        }
    }

    bool OpenPipeForRead()
    {
        return OpenPipe(READ);
    }

    bool OpenPipeForWrite()
    {
        return OpenPipe(WRITE);
    }

    int ReadForFifo(std::string* out)
    {
        char buffer[MAXSIZE];
        int n = read(_fd, buffer, MAXSIZE - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    int WriteToFifo(const std::string& in)
    {
        return write(_fd, in.c_str(), in.size());
    }

    int GetFd()
    {
        return _fd;
    }

    std::string GetPath()
    {
        return _fifoPath;
    }

private:
    bool OpenPipe(int mode)
    {
        _fd = open(_fifoPath.c_str(), mode);
        if (_fd < 0)
            return false;
        return true;
    }

private:
    std::string _fifoPath;
    character _ch;
    int _fd;
};